//
//  My_Release.m
//  HappyStore
//
//  Created by 点点充 on 16/1/26.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "My_Release.h"
#define TOPHEIGHT 50

@interface My_Release ()
{
    NSArray *aryItem;
    UIView *_slideView;
    
    NSMutableArray *muAryData;
    
    NSInteger paggge;
    
    NSInteger _currentPage;
}
@end

@implementation My_Release

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _currentPage = 0;
    
    _labBack.backgroundColor = [UIColor colorWithWhite:0.8f alpha:1.f];
    if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人
        aryItem = @[@"项目",@"资金",@"服务",@"求职",@"活动"];
    }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2 ){//企业
        aryItem = @[@"项目",@"资金",@"服务",@"招聘",@"活动"];
    }else {
        aryItem = @[@"项目",@"活动"];
    }
    
    [self addTopButton];
    
    
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSString *path = [[NSBundle mainBundle]pathForResource:@"refresh"
                                                        ofType:@"wav"];
        SystemSoundID soundID;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
        AudioServicesPlaySystemSound(soundID); //仅播放音频
        paggge = 1;
        [self startSearch];
    }];
    
    _mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        paggge += 1;
        [self startSearch];
    }];
    _mainTableView.mj_footer.hidden = YES;

    paggge = 1;
    [self startSearch];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}

- (void)addTopButton
{
    CGFloat width = self.view.frame.size.width / aryItem.count;
    _topScrollView.showsHorizontalScrollIndicator = NO;
    _topScrollView.showsVerticalScrollIndicator = YES;
    _topScrollView.contentSize = CGSizeMake(width * aryItem.count, TOPHEIGHT);
    
    for (int i = 0; i < aryItem.count; i ++) {
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * width, 0, width, TOPHEIGHT)];
        button.tag = i;
        [button setTitle:aryItem[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(tabButton:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor colorWithRed:89/255.f green:87/255.f blue:87/255.f alpha:1.f] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:13.f];
        [_topScrollView addSubview:button];
    }
    
    [self initSlideView];
}


- (void)tabButton:(UIButton *)sender
{
    CGRect frame = _slideView.frame;
    frame.origin.x = sender.frame.origin.x;
    _slideView.frame = frame;
    
    _currentPage = sender.tag;
    // 马上进入刷新状态
    [_mainTableView.mj_header beginRefreshing];
    //顶部跟着滑动
    [_topScrollView scrollRectToVisible:CGRectMake(sender.frame.origin.x-sender.frame.size.width*2, 0, _topScrollView.frame.size.width, _topScrollView.frame.size.height) animated:YES];
}

#pragma mark -- 初始化滑动的指示View
-(void) initSlideView {
    
    CGFloat width = self.view.frame.size.width / aryItem.count;
    
    _slideView = [[UIView alloc] initWithFrame:CGRectMake(0, TOPHEIGHT - 5, width, 5)];
    [_slideView setBackgroundColor:[UIColor colorWithRed:32/255.f green:165/255.f blue:240/255.f alpha:1.f]];
    [_topScrollView addSubview:_slideView];
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:muAryData.count];
    return muAryData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_currentPage == 3) {
        return 120;
    }else {
        return 110;
    }
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cell2 = @"cell2";
    static NSString *cell3 = @"cell3";
    
    
    if (_currentPage == 3) {
        BOOL nibsRegistered2 = NO;
        if (!nibsRegistered2) {
            UINib *nib=[UINib nibWithNibName:@"TableViewCell3" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:cell3];
            nibsRegistered2=YES;
        }
        
        NSLog(@"%ld",indexPath.row);
        TableViewCell3 *cell = [tableView dequeueReusableCellWithIdentifier:cell3];
        UIView *viewBack = [cell viewWithTag:50];
        viewBack.layer.masksToBounds = YES;
        viewBack.layer.borderColor = [UIColor colorWithWhite:0.8 alpha:1.0f].CGColor;
        viewBack.layer.borderWidth = 0.5f;
        
        
        UIImageView *imgHeader = [cell viewWithTag:51];
        [imgHeader sd_setImageWithURL:[NSURL URLWithString:muAryData[indexPath.row][@"headPhoto"]] placeholderImage:[UIImage imageNamed:@"img_normal3"]];
        imgHeader.layer.masksToBounds = YES;
        imgHeader.layer.cornerRadius = 23.f;
        
        UILabel *labUserName = [cell viewWithTag:52];
        if (muAryData[indexPath.row][@"username"] == [NSNull null] || [muAryData[indexPath.row][@"username"] isEqualToString:@"null"]) {
            labUserName.text = muAryData[indexPath.row][@"account"];
        }else {
            labUserName.text = muAryData[indexPath.row][@"username"];
        }
        
        //进用户详情
        UIButton *btnHeader = [cell viewWithTag:53];
        
        UILabel *labTitle = [cell viewWithTag:10];
        labTitle.text = muAryData[indexPath.row][@"title"];
        
        //薪资
        UILabel *labPrice = [cell viewWithTag:11];
        labPrice.text = [CustomExcetion comperNumber:muAryData[indexPath.row][@"money"]];
        
        //经验
        UILabel *labExperience = [cell viewWithTag:12];
        labExperience.text = muAryData[indexPath.row][@"experience"];
        
        //学历
        UILabel *labDegree = [cell viewWithTag:13];
        labDegree.text = muAryData[indexPath.row][@"schooling" ];
        
        //职位
        UILabel *labPosition = [cell viewWithTag:14];
        labPosition.text = muAryData[indexPath.row][@"positionName"];
        
        //行业
        UILabel *labIndustry = [cell viewWithTag:15];
        labIndustry.text = muAryData[indexPath.row][@"industry"];
        
        
        //发布时间
        UILabel *labReleaseDate = [cell viewWithTag:16];
        labReleaseDate.text = [CustomExcetion prettyDateWithReference:[CustomExcetion dateFromString:muAryData[indexPath.row][@"createTime"]]];
        
        //工作地点
        UILabel *labWorkPlace = [cell viewWithTag:17];
        labWorkPlace.text = muAryData[indexPath.row][@"addresss"];
        
        return cell;
    }else {
        BOOL nibsRegistered3 = NO;
        if (!nibsRegistered3) {
            UINib *nib=[UINib nibWithNibName:@"TableViewCell2" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:cell2];
            nibsRegistered3=YES;
        }
        
        NSLog(@"%ld",indexPath.row);
        TableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:cell2];
        
        UIButton *btn = [cell viewWithTag:10];//lable
        btn.userInteractionEnabled = NO;
        if (muAryData[indexPath.row][@"lable"] == [NSNull null] || [muAryData[indexPath.row][@"lable"] isEqualToString:@"null"]) {
            btn.hidden = YES;
        }else {
            NSString *_string = muAryData[indexPath.row][@"lable"];
            NSArray *_arr = [_string componentsSeparatedByString:NSLocalizedString(@",", nil)];
            [btn setTitle:_arr[0] forState:UIControlStateNormal];
        }
        
        
        UIImageView *imgV = [cell viewWithTag:20];
        [imgV sd_setImageWithURL:[NSURL URLWithString:muAryData[indexPath.row][@"logo"]] placeholderImage:[UIImage imageNamed:@"img_normal3"]];
        imgV.layer.masksToBounds = YES;
        imgV.layer.cornerRadius = 5.f;
        
        UILabel *labTitle = [cell viewWithTag:21];
        labTitle.text = muAryData[indexPath.row][@"title"];
        
        UILabel *labPrice = [cell viewWithTag:22];
        labPrice.text = [CustomExcetion comperNumber:muAryData[indexPath.row][@"investment"]];
        
        UILabel *labAddress = [cell viewWithTag:23];
        labAddress.text = muAryData[indexPath.row][@"address"];
        
        UILabel *labPeople = [cell viewWithTag:24];
        if (muAryData[indexPath.row][@"username"] == [NSNull null] || [muAryData[indexPath.row][@"username"] isEqualToString:@"null"]) {
            labPeople.text = muAryData[indexPath.row][@"account"];
        }else {
            labPeople.text = muAryData[indexPath.row][@"username"];
        }
        
        
        UILabel *labDate = [cell viewWithTag:25];
        NSDate *date = [CustomExcetion dateFromString:muAryData[indexPath.row][@"createtime"]];
        labDate.text = [CustomExcetion prettyDateWithReference:date];
        
        return cell;
    }
    
    
    
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    
    switch (_currentPage) {
        case 0://项目
        {
            Project_Detail *project_detail = [self.storyboard instantiateViewControllerWithIdentifier:@"project_detail"];
            project_detail.projectId = muAryData[indexPath.row][@"projectId"];
            [self.navigationController pushViewController:project_detail animated:YES];
        }
            break;
        case 1://资金、活动
        {
            if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 3 ){//政府：活动
                BusinessActivity_Detail *business_Detail = [self.storyboard instantiateViewControllerWithIdentifier:@"business_detail"];
                business_Detail.activityId = muAryData[indexPath.row][@"activityId"];
                [self.navigationController pushViewController:business_Detail animated:YES];
            }else {//资金
                SearchPrice_Detail *SearchPrice_Detail = [self.storyboard instantiateViewControllerWithIdentifier:@"SearchPrice_Detail"];
                SearchPrice_Detail.fundsId = muAryData[indexPath.row][@"fundsId"];
                [self.navigationController pushViewController:SearchPrice_Detail animated:YES];
            }
        }
            break;
        case 2://服务
        {
            SoftwareDevelop_Detail *SoftwareDevelop_Detail = [self.storyboard instantiateViewControllerWithIdentifier:@"SoftwareDevelop_Detail"];
            SoftwareDevelop_Detail.projectId = muAryData[indexPath.row][@"serviceId"];
            [self.navigationController pushViewController:SoftwareDevelop_Detail animated:YES];
        }
            break;
            
        case 3://招聘、求职
        {//type=类型 1招聘 2求职
            
            Recruitment_Detail *recruitment = [self.storyboard instantiateViewControllerWithIdentifier:@"recruitment_Detail"];
            recruitment.projectId = muAryData[indexPath.row][@"jobId"];
            if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人
                //招聘
                recruitment.strType = @"2";
            }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==2 ){//企业
                //求职
                recruitment.strType = @"1";
            }
            [self.navigationController pushViewController:recruitment animated:YES];
        }
            break;
        case 4://活动
        {
            BusinessActivity_Detail *business_Detail = [self.storyboard instantiateViewControllerWithIdentifier:@"business_detail"];
            business_Detail.activityId = muAryData[indexPath.row][@"activityId"];
            [self.navigationController pushViewController:business_Detail animated:YES];
        }
            break;
    }
    
    
}

#pragma mark - 获取数据
- (void)startSearch
{
    
    //token=验证用户&page=页码&userId=用户id
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
    [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];
    
    NSString *strURl = @"";
    
    switch (_currentPage) {
        case 0://项目
        {
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getMyoutProject_app_myHome.im.lensum"];
        }
            break;
        case 1://资金、活动
        {
            if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 3 ){//政府：活动
                strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getMyoutActivity_app_myHome.im.lensum"];
            }else {//资金
                strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getMyoutFunds_app_myHome.im.lensum"];
            }
        }
            break;
        case 2://服务
        {
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getMyoutService_app_myHome.im.lensum"];
        }
            break;
        case 3://招聘、求职
        {//type=类型 1招聘 2求职
            if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人:求职
                [muDicParameters setObject:@"2" forKey:@"type"];
            }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2 ){//企业：招聘
                [muDicParameters setObject:@"1" forKey:@"type"];
            }
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getMyoutJobhunting_app_myHome.im.lensum"];
        }
            break;
        case 4://活动
        {
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getMyoutActivity_app_myHome.im.lensum"];
        }
            break;
    }
    
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [_mainTableView.mj_header endRefreshing];
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        NSLog(@"%@",dicInfo);
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            [_mainTableView.mj_header endRefreshing];
            if (paggge == 1) {
                muAryData = [NSMutableArray arrayWithArray:[dicInfo objectForKey:@"data"][@"record"]];
                
                if (muAryData.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }else {
                NSArray *ary11 = [dicInfo objectForKey:@"data"][@"record"];
                for (int i = 0; i<ary11.count; i++) {
                    NSDictionary *dic1 = ary11[i];
                    [muAryData addObject:dic1];
                }
                if (ary11.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }
            
            
            [_mainTableView reloadData];
            [SVProgressHUD dismiss];
        }else {
            if (paggge == 1) {
                muAryData = [NSMutableArray array];
            }
            
            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];

        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [_mainTableView.mj_header endRefreshing];
        [_mainTableView.mj_footer endRefreshing];
        if (paggge == 1) {
            muAryData = [NSMutableArray array];
            [_mainTableView reloadData];
        }

       [self showSingleIconBubble:error.localizedDescription];

    }];
}


//侧滑－－删除
//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self startDeleteWithId:indexPath];
    
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}


#pragma mark - 删除数据
- (void)startDeleteWithId:(NSIndexPath *)indexPath
{
    [self showRoundProgressWithTitle:@"请稍后..."];
    //token=验证用户&page=页码&userId=用户id
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
    
    
    NSString *strURl = @"";
    
    switch (_currentPage) {
        case 0://项目
        {
            [muDicParameters setObject:muAryData[indexPath.row][@"projectId"] forKey:@"projectId"];
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"deleteMyProject_app_myHome.im.lensum"];
        }
            break;
        case 1://资金、活动
        {
            if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 3 ){//政府：活动
                //activityId
                [muDicParameters setObject:muAryData[indexPath.row][@"activityId"] forKey:@"activityId"];
                strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"deleteMyActivity_app_myHome.im.lensum"];
            }else {//资金
                //fundsId
                [muDicParameters setObject:muAryData[indexPath.row][@"fundsId"] forKey:@"fundsId"];
                strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"deleteMyFunds_app_myHome.im.lensum"];
            }
        }
            break;
        case 2://服务
        {
            //serviceId
            [muDicParameters setObject:muAryData[indexPath.row][@"serviceId"] forKey:@"serviceId"];
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"deleteMyService_app_myHome.im.lensum"];
        }
            break;
        case 3://招聘、求职
        {//type=类型 1招聘 2求职
            if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人:求职
                [muDicParameters setObject:@"2" forKey:@"type"];
            }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2 ){//企业：招聘
                [muDicParameters setObject:@"1" forKey:@"type"];
            }
            //jobId
            [muDicParameters setObject:muAryData[indexPath.row][@"jobId"] forKey:@"jobId"];
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"deleteMyJobhunting_app_myHome.im.lensum"];
        }
            break;
        case 4://活动
        {
            [muDicParameters setObject:muAryData[indexPath.row][@"activityId"] forKey:@"activityId"];
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"deleteMyActivity_app_myHome.im.lensum"];
        }
            break;
    }
    
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//        NSLog(@"%@",dicInfo);

        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            [muAryData removeObjectAtIndex:indexPath.row];
            [_mainTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

            [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
        }else {

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
            
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

       [self showSingleIconBubble:error.localizedDescription];

    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
